using System;
using System.Collections;
using System.Data;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using PHSRAG.Insight21.CDS;
using PHSRAG.Insight21.Common.Pages;
using PHSRAG.Insight21.Context;
using PHSRAG.Insight21.FormsManagement;
using PHSRAG.Insight21.Policy;
using PHSRAG.Security.Enumerations;
using PHSRAG.Utility;
using Calendar = PHSRAG.WebControls.Calendar;
using Utils = PHSRAG.Insight21.InsightUtilities;

namespace PHSRAG.Insight21.COI
{
    /// <summary>
    /// This page will be used as a reporting tool for the insight user having super user access rights.
    /// The Super-user can search on various parameters to run a report on the specic criteria.
    /// Note:This page avails the user to search across the charts as well as restricting the search only to certain charts.
    /// </summary>
    public partial class COICustomReport : BasePage
    {
        #region Constants

        private const string AnnunciatorTitle = "The following error(s) occurred...";
        private const string CustomReportPageIndexKey = "CustomReportPageIndexKey_F7A68FB0-3AF0-48fc-A3B2-379B85B18AB9";

        /// <summary>
        /// Id column(Datkey column) for the data source
        /// </summary>
        private const string KeyField = "Id";

        /// <summary>
        /// Referring page identifier
        /// </summary>
        private const int ReferrencePageIndex = 4;

        private const string SqlReportingParamNameXml = "xml";

        #endregion

        # region Private Variables

        private ICachePolicy cachePolicy;

        /// <summary>
        /// Page cache policy
        /// </summary>
        private ICachePolicy pageCachePolicy;

        #endregion

        #region Private Properties

        /// <summary> 
        /// Gets the COIUserSummary object relevant to the passed in search criteria.
        /// </summary>
        private COIUserSummary COIUserSummary
        {
            get
            {
                COIUserSummary cOIUserSummary = GetCOIUserSummaryFromCache ?? new COIUserSummary(cachePolicy);

                cOIUserSummary.Load(DataAccess.ConnectionString, GetSeachCriteriaHash(), selectChart.Items[0].Selected, selectChart.Items[1].Selected, selectChart.Items[2].Selected, selectChart.Items[3].Selected, selectOutsideTrusteeChart.Items[0].Selected, selectOutsideTrusteeChart.Items[1].Selected);
                cOIUserSummary.Cache();

                return cOIUserSummary;
            }
        }

        /// <summary>
        /// Get/Set the current page within the datagrid for display. This information persists across page loads.
        /// </summary>
        private int CurrentPageIndex
        {
            get
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.CustomReportPageKey) as Hashtable;
                return (h == null || h[CustomReportPageIndexKey] == null) ? 0 : (int) h[CustomReportPageIndexKey];
            }
            set
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.CustomReportPageKey) as Hashtable ?? new Hashtable();
                h[CustomReportPageIndexKey] = value;
                coiReportGrid.CurrentPageIndex = value;
                pageCachePolicy.Cache(Keys.CustomReportPageKey, h);
            }
        }

        /// <summary>
        /// Gets the Cached COIUserSummary object
        /// </summary>
        private COIUserSummary GetCOIUserSummaryFromCache
        {
            get { return cachePolicy.GetCachedObject(COIUserSummary.CacheKey) as COIUserSummary; }
        }

        #endregion

        #region Event Handlers

        protected void OnPageLoad(object sender, EventArgs e)
        {
            try
            {
                annunciator.Message = string.Empty;
                annunciator.Title = string.Empty;

                breadCrumb.Add("Custom Reports", Settings.
                    GetKeyValue("SubNavigation.CoI.CustomReportURL", string.Empty),
                    Settings.GetKeyValue("BreadCrumb.SummaryPageLevel", 1));
                if (!IsPostBack)
                {
                    // Set pdf/excel download bar values
                    downloadBar.ReportHostPage = Settings.GetKeyValue(Common.Constants.ConfigKeyReportHostPageCoi, Settings.GetKeyValue(Common.Constants.ConfigKeyReportHostPage, string.Empty));
                    downloadBar.SQLReportName = SSRSRequest.ReportNames.Coi.CustomReports;

                    /*Remove PostBack from summaryReport */
                    detailedReport.OnClientClick = "javascript:window.open('../Research/DownloadForm.aspx?Report=coidtreport', 'supervisorReport', 'resizable=yes, status=yes, scrollbars=yes');return false;";
                    summaryReport.OnClientClick = "javascript:window.open('../Research/DownloadForm.aspx?Report=coisumreport', 'supervisorReport', 'resizable=yes, status=yes, scrollbars=yes');return false;";

                    LoadControls();
                }
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
            finally
            {
                coiSubNavigation.SelectedLink = "Custom Reports";
                coiSubNavigation.AccessLevel = ((UserContext) cachePolicy.GetCachedObject(UserContext.CacheKey)).ModuleRoleBitmask;
            }
        }

        private void OnSearch(object sender, ImageClickEventArgs e)
        {
            try
            {
                InitializePager();
                LoadDataGrid();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// This event is raised when the page index property is changed on the pager control.
        /// The page's DataGrid is reloaded with the data belonging to page specified by the index.
        /// </summary>
        /// <param name="source">The object raising an event.</param>
        /// <param name="e">Argument associated with the event</param>
        private void OnPageIndexChanged(object source, DataGridPageChangedEventArgs e)
        {
            try
            {
                coiReportGrid.CurrentPageIndex = e.NewPageIndex;
                LoadDataGrid();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Occurs when the FirstPage hyperlink is clicked on the pager.
        /// The page's DataGrid is reloaded with the data belonging to the first page.
        /// </summary>
        /// <param name="sender">The object raising an event.</param>
        /// <param name="e">Argument associated with the event</param>
        private void OnFirstPage(object sender, CommandEventArgs e)
        {
            try
            {
                CurrentPageIndex = 0;
                LoadDataGrid();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Occurs when the LastPage hyperlink is clicked on the pager.
        /// The page's DataGrid is reloaded with the data belonging to the last page.
        /// </summary>
        /// <param name="sender">The object raising an event.</param>
        /// <param name="e">Argument associated with the event</param>
        private void OnLastPage(object sender, CommandEventArgs e)
        {
            try
            {
                int lastPageIndex = topPager.PageCount - 1;
                CurrentPageIndex = lastPageIndex;
                LoadDataGrid();
            }

            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Occurs when the NextPage hyperlink is clicked on the pager.
        /// The page's DataGrid is reloaded with the data belonging to the next page.
        /// </summary>
        /// <param name="sender">The object raising an event.</param>
        /// <param name="e">Argument associated with the event</param>
        private void OnNextPage(object sender, CommandEventArgs e)
        {
            try
            {
                ++CurrentPageIndex;
                LoadDataGrid();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Occurs when the PreviousPage hyperlink is clicked on the pager.
        /// The page's DataGrid is reloaded with the data belonging to the previous page.
        /// </summary>
        /// <param name="sender">The object raising an event.</param>
        /// <param name="e">Argument associated with the event</param>
        private void OnPreviousPage(object sender, CommandEventArgs e)
        {
            try
            {
                --CurrentPageIndex;
                LoadDataGrid();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Resets the subnavigation selected link(s) before the 
        /// header changes/breadcrumb navigation.
        /// </summary>
        /// <param name="sender">Control which rasied the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        private void OnNavigate(object sender, CommandEventArgs e)
        {
            try
            {
                PurgeCache();
                coiSubNavigation.Reset();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Purges the cache before the COI subnavigation header performs a redirect.
        /// </summary>
        /// <param name="sender">Control which rasied the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        private void OnSubNavigate(object sender, CommandEventArgs e)
        {
            try
            {
                PurgeCache();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Event raised on binding the datasource to the grid
        /// </summary>
        /// <param name="sender">owner of the event</param>
        /// <param name="e">arguments with respect to the event</param>
        private void OnItemDataBound(object sender, DataGridItemEventArgs e)
        {
            try
            {
                if ((e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem))
                {
                    e.Item.Cells[(int) ColumnIndex.PolicyQuestion].Text = (e.Item.Cells[(int) ColumnIndex.PolicyQuestion].Text.ToLower() == "true") ? "*" : "";
                    e.Item.Cells[(int) ColumnIndex.OutsideActivity].Text = (e.Item.Cells[(int) ColumnIndex.OutsideActivity].Text.ToLower() == "true") ? "Y" : (e.Item.Cells[(int) ColumnIndex.OutsideActivity].Text.ToLower() == "false") ? "N" : "";
                    e.Item.Cells[(int) ColumnIndex.OtherActivity].Text = (e.Item.Cells[(int) ColumnIndex.OtherActivity].Text.ToLower() == "true") ? "Y" : (e.Item.Cells[(int) ColumnIndex.OtherActivity].Text.ToLower() == "false") ? "N" : "";
                    e.Item.Cells[(int) ColumnIndex.EquityInterest].Text = (e.Item.Cells[(int) ColumnIndex.EquityInterest].Text.ToLower() == "true") ? "Y" : (e.Item.Cells[(int) ColumnIndex.EquityInterest].Text.ToLower() == "false") ? "N" : "";
                    e.Item.Cells[(int) ColumnIndex.FamilyInterset].Text = (e.Item.Cells[(int) ColumnIndex.FamilyInterset].Text.ToLower() == "true") ? "Y" : (e.Item.Cells[(int) ColumnIndex.FamilyInterset].Text.ToLower() == "false") ? "N" : "";
                    e.Item.Cells[(int) ColumnIndex.Royalty].Text = (e.Item.Cells[(int) ColumnIndex.Royalty].Text.ToLower() == "true") ? "Y" : (e.Item.Cells[(int) ColumnIndex.Royalty].Text.ToLower() == "false") ? "N" : "";
                    ((LinkButton) e.Item.Cells[(int) ColumnIndex.CurrentCOI].Controls[0]).Text = (e.Item.Cells[(int) ColumnIndex.DocumentId].Text == "&nbsp;") ? "" : "<img src='../Images/pdf.jpg' border=0 height='20px' />";

                    /*Remove postback for opening Current COI*/

                    ((LinkButton) e.Item.Cells[(int) ColumnIndex.CurrentCOI].Controls[0]).OnClientClick = "javascript:window.open('../Research/DownloadForm.aspx?Report=ViewReport&DocId=" + e.Item.Cells[(int) ColumnIndex.DocumentId].Text + "', 'ViewReport', 'resizable=yes, status=yes, scrollbars=yes');return false;";
                }
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Event raised on performing actions on the datagrid
        /// </summary>
        /// <param name="sender">owner of the event</param>
        /// <param name="e">arguments with respect to the event</param>
        //private void OnItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
        //{
        //    try
        //    {			
        //        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        //        {
        //            if (e.CommandName=="OpenCurrentCOI")
        //            {
        //                Hashtable outgoingCache = pageCachePolicy.GetCachedObject(Keys.IncomingDataKey) as Hashtable;
        //                if (outgoingCache == null)
        //                    outgoingCache = new Hashtable();
        //                Document report = new Document(cachePolicy);
        //                report.Load(Utility.DataAccess.ConnectionString, Convert.ToInt32(e.Item.Cells[(int)ColumnIndex.DocumentId].Text));
        //                outgoingCache[Keys.DocumentKey] = report;
        //                pageCachePolicy.Cache(Keys.IncomingDataKey, outgoingCache);
        //                //Script for popup window that displays the attachment
        //                string script = "\n<script language=JavaScript id='displayAttachment'>\n" + 
        //                    "var confirmWin = null; \n" +
        //                    "winId = window.open('','customReport');" +
        //                    "if (winId != null) winId.close();" +
        //                    "confirmWin = window.open('../Research/DownloadForm.aspx', 'customReport', 'resizable=yes, status=yes, scrollbars=yes'); \n" +
        //                    "</script>";
        //                //Check whether the script is already registered
        //                if(!this.ClientScript.IsClientScriptBlockRegistered("DisplayAttachment"))
        //                {
        //                    //Register the script
        //                    this.ClientScript.RegisterClientScriptBlock(GetType( ), "DisplayAttachment",script);
        //                }
        //            }
        //        }
        //    }			
        //    catch(Exception ex)
        //    {
        //        DisplayExceptionReport(ex);
        //    }
        //}
        /// <summary>
        /// Handler for event raised while each data grid item is created.
        /// If the item being created is the data grid header, do the following:
        /// Add the appropriate sort symbol to denote ascending/descending sequence for the current sort column.
        /// This requires us to locate the cell which corresponding to the column within the collection of TableCell
        /// maintained by the DataGridItem which is under creation. That collection is indexed numerically, the value being
        /// the position of the column within the columns collection maintained by the data grid.
        /// One simple way to do this is to create static mapping between the name of the column and its index. However, this
        /// suffers from the shortcoming that if the sequence of columns is changed on the page, the static binding MUST
        /// be changed too. If they get out of sync, we would be sorting on inappropriate columns!
        /// To avoid this, and to render the code independent of how the page gets managed, we will build a Hashtable of
        /// column indeces, keyed by the sort expression of each column. That way, we could do a quick lookup to get the
        /// index of a column and set the sort symbol on that column.
        /// If the item being created is a data row item, disable its view state.
        /// </summary>
        /// <param name="sender">Control which raised the event</param>
        /// <param name="e">Argument associated with the event</param>
        private void OnItemCreated(object sender, DataGridItemEventArgs e)
        {
            try
            {
                if (e.Item.ItemType == ListItemType.Header)
                {
                    COIUserSummary cOIUserSummary = GetCOIUserSummaryFromCache;
                    Label sortSymbol = new Label();
                    sortSymbol.Text = (cOIUserSummary.SortAscending) ? InsightUtilities.Constants.SortAscendingText : InsightUtilities.Constants.SortDescendingText;
                    sortSymbol.Font.Name = InsightUtilities.Constants.SortSymbolFontName;

                    Hashtable columnMap = new Hashtable();
                    foreach (DataGridColumn column in coiReportGrid.Columns)
                    {
                        columnMap[column.SortExpression] = coiReportGrid.Columns.IndexOf(column);
                    }

                    string sortColumn = cOIUserSummary.SortColumn;
                    if (columnMap.ContainsKey(sortColumn))
                    {
                        (e.Item.Cells[(int) columnMap[sortColumn]]).Controls.Add(sortSymbol);
                    }
                }
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Sort event handler
        /// </summary>
        /// <param name="source">The object raising an event.</param>
        /// <param name="e">Argument associated with the event</param>
        private void OnSort(object source, DataGridSortCommandEventArgs e)
        {
            try
            {
                if (e.SortExpression != string.Empty)
                {
                    COIUserSummary cOIUserSummary = GetCOIUserSummaryFromCache ?? new COIUserSummary(cachePolicy);

                    cOIUserSummary.SortColumn = e.SortExpression;
                    cOIUserSummary.SortAscending = (cOIUserSummary.SortColumn == e.SortExpression) ? !cOIUserSummary.SortAscending : cOIUserSummary.SortAscending;
                    cOIUserSummary.Cache();
                    CurrentPageIndex = 0;
                    LoadDataGrid();
                }
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// EventHandler for individual chart selection(CheckBoxList)
        /// </summary>
        /// <param name="sender">The object raising an event.</param>
        /// <param name="e">Argument associated with the event</param>
        protected void OnSelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                gridContainer.Visible = false;

                if (selectChart.Items[0].Selected)
                {
                    searchChart1.Visible = true;
                    selectOutsideTrusteeChart.Items[0].Selected = false;
                    selectOutsideTrusteeChart.Items[1].Selected = false;
                    selectOutsideTrusteeChart.Enabled = false;
                }
                else
                {
                    searchChart1.Visible = false;
                }

                if (selectChart.Items[1].Selected)
                {
                    selectOutsideTrusteeChart.Items[0].Selected = false;
                    selectOutsideTrusteeChart.Items[1].Selected = false;
                    searchChart2.Visible = true;
                    selectOutsideTrusteeChart.Enabled = false;
                }
                else
                {
                    searchChart2.Visible = false;
                }
                if (selectChart.Items[2].Selected)
                {
                    selectOutsideTrusteeChart.Items[0].Selected = false;
                    selectOutsideTrusteeChart.Items[1].Selected = false;
                    searchChart3.Visible = true;
                    selectOutsideTrusteeChart.Enabled = false;
                }
                else
                {
                    searchChart3.Visible = false;
                }

                if (selectChart.Items[3].Selected)
                {
                    searchChart4.Visible = true;
                    selectOutsideTrusteeChart.Items[0].Selected = false;
                    selectOutsideTrusteeChart.Items[1].Selected = false;
                    selectOutsideTrusteeChart.Enabled = false;
                }
                else
                {
                    searchChart4.Visible = false;
                }

                if (!selectChart.Items[0].Selected &&
                    !selectChart.Items[1].Selected &&
                        !selectChart.Items[2].Selected &&
                            !selectChart.Items[3].Selected)
                {
                    selectOutsideTrusteeChart.Enabled = true;
                }
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// event handler to handle trustee chart selection
        /// </summary>
        /// <param name="sender">The object raising an event.</param>
        /// <param name="e">Argument associated with the event</param>
        protected void OnOutsideTrusteeChartSelectionChanged(object sender, EventArgs e)
        {
            try
            {
                if (selectOutsideTrusteeChart.Items[0].Selected)
                {
                    outsideTrusteeChart.Visible = true;
                    selectChart.Items[0].Selected = false;
                    selectChart.Items[1].Selected = false;
                    selectChart.Items[2].Selected = false;
                    selectChart.Enabled = false;
                }
                else
                {
                    outsideTrusteeChart.Visible = false;
                }

                if (selectOutsideTrusteeChart.Items[1].Selected)
                {
                    selectChart.Items[0].Selected = false;
                    selectChart.Items[1].Selected = false;
                    selectChart.Items[2].Selected = false;
                    selectChart.Enabled = false;
                    outsideTrusteeChart.Visible = true;
                    associatedFamilyMember.Enabled = true;
                }
                else
                {
                    outsideTrusteeChart.Visible = (selectOutsideTrusteeChart.Items[0].Selected) ? true : false;
                    associatedFamilyMember.Enabled = false;
                }

                if (!selectOutsideTrusteeChart.Items[1].Selected && !selectOutsideTrusteeChart.Items[0].Selected)
                {
                    selectChart.Enabled = true;
                }
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Reseta the custom search selections
        /// </summary>
        /// <param name="sender">The object raising an event.</param>
        /// <param name="e">Argument associated with the event</param>
        private void OnReset(object sender, ImageClickEventArgs e)
        {
            ResetSearchCriteria(containerPanel);
        }

        #endregion

        #region Web Form Designer generated code

        protected override void OnInit(EventArgs e)
        {
            try
            {
                InitializeComponent();
                base.OnInit(e);
                cachePolicy = (Policy.ICachePolicy) Session[Policy.Names.CachePolicyKey];
                pageCachePolicy = (Policy.ICachePolicy) Session[Policy.Names.PageCachePolicyKey];
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.header.Navigate += new System.Web.UI.WebControls.CommandEventHandler(this.OnNavigate);
            this.reset.Click += new ImageClickEventHandler(OnReset);
            this.search.Click += new ImageClickEventHandler(OnSearch);
            this.topPager.FirstPage += new System.Web.UI.WebControls.CommandEventHandler(this.OnFirstPage);
            this.topPager.PreviousPage += new System.Web.UI.WebControls.CommandEventHandler(this.OnPreviousPage);
            this.topPager.NextPage += new System.Web.UI.WebControls.CommandEventHandler(this.OnNextPage);
            this.topPager.LastPage += new System.Web.UI.WebControls.CommandEventHandler(this.OnLastPage);
            this.coiReportGrid.ItemCreated += new System.Web.UI.WebControls.DataGridItemEventHandler(this.OnItemCreated);
            //this.coiReportGrid.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.OnItemCommand);
            this.coiReportGrid.PageIndexChanged += new System.Web.UI.WebControls.DataGridPageChangedEventHandler(this.OnPageIndexChanged);
            this.coiReportGrid.SortCommand += new System.Web.UI.WebControls.DataGridSortCommandEventHandler(this.OnSort);
            this.coiReportGrid.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.OnItemDataBound);
            this.bottomPager.FirstPage += new System.Web.UI.WebControls.CommandEventHandler(this.OnFirstPage);
            this.bottomPager.PreviousPage += new System.Web.UI.WebControls.CommandEventHandler(this.OnPreviousPage);
            this.bottomPager.NextPage += new System.Web.UI.WebControls.CommandEventHandler(this.OnNextPage);
            this.bottomPager.LastPage += new System.Web.UI.WebControls.CommandEventHandler(this.OnLastPage);
            //this.detailedReport.Click += new ImageClickEventHandler(OnDetailedReport);
            //this.summaryReport.Click += new ImageClickEventHandler(OnSummaryReport);
            this.Load += new System.EventHandler(this.OnPageLoad);
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// This method loads all the controls with respective item options.
        /// </summary>
        private void LoadControls()
        {
            LoadRole();
            Hashtable coiQuestionnaireCollection = Questionnaire.GetQuestionnaires((int) ModuleBit.COI, cachePolicy);
            foreach (Questionnaire q in coiQuestionnaireCollection.Values)
            {
                QuestionnaireVersion qv = Questionnaire.GetActiveVersion(cachePolicy, q.Name, q.Type);
                if (qv != null)
                {
                    switch (q.Name.ToLower().Trim())
                    {
                        case COI.Constants.COIFormsInLowerCase.YourOutsideActivities:
                        {
                            Hashtable controlCollection = new Hashtable();
                            controlCollection.Add("public", companyType);
                            controlCollection.Add("BriefDescriptionofBusiness", bussinessNatureOfOutsideEntity);
                            controlCollection.Add("AnnualCashComp", incomeOutsideActivity);
                            controlCollection.Add("AnnualEquity", annualEquity);
                            controlCollection.Add("TotalEquityOwned", equityOwned);
                            controlCollection.Add("Position", selectPosition);
                            controlCollection.Add("TotalPercentEquityOwned", perTotalEquityOwned);
                            controlCollection.Add("WrittenAgreement", selectWrittenAgreementAnswered);
                            controlCollection.Add("CSRL", csrlReview);
                            controlCollection.Add("DescrServiceProvide", serviceType);

                            AddOptionsToControl(qv, controlCollection);
                            break;
                        }
                        case COI.Constants.COIFormsInLowerCase.YourEquityInterests:
                        {
                            Hashtable controlCollection = new Hashtable();
                            controlCollection.Add("ValueOfEquity", equityinterest);
                            AddOptionsToControl(qv, controlCollection);
                            break;
                        }
                        case COI.Constants.COIFormsInLowerCase.YourFamilyInterests:
                        {
                            Hashtable controlCollection = new Hashtable();
                            controlCollection.Add("FamilyMemberType", memberAssosiated);
                            controlCollection.Add("FamilyMemberRelationship", memberRelation);
                            controlCollection.Add("ValueOfEquity", valueEquityInterest);
                            AddOptionsToControl(qv, controlCollection);
                            break;
                        }
                        case COI.Constants.COIFormsInLowerCase.TrusteeFamilyAssociations:
                        {
                            Hashtable controlCollection = new Hashtable();
                            controlCollection.Add("FamilyMemberRelationship", nonPartnerAssociation);
                            controlCollection.Add("BriefDescriptionofBusiness", briefDescOfNonPartnersEntity);
                            controlCollection.Add("FamilyMemberType", associatedFamilyMember);
                            AddOptionsToControl(qv, controlCollection);
                            break;
                        }
                        case COI.Constants.COIFormsInLowerCase.YourIntellectualProperty:
                        {
                            Hashtable controlCollection = new Hashtable();
                            controlCollection.Add("Payment", isPayedByPartners);
                            controlCollection.Add("NaturePayments", paymentNature);
                            controlCollection.Add("PurposePayments", paymentPurpose);
                            controlCollection.Add("AnnualPayment", annulaPayment);
                            AddOptionsToControl(qv, controlCollection);
                            break;
                        }
                        default:
                            break;
                    }
                }
            }
        }

        /// <summary>
        /// Displays an error message on the screen to the user with the exception, and all
        /// inner exception messages.
        /// </summary>
        /// <param name="ex">The exception to report on</param>
        private void DisplayExceptionReport(Exception ex)
        {
            annunciator.Title = AnnunciatorTitle;
            annunciator.Message = ExceptionReport.GetExceptionInfo(ex, false);
        }

        /// <summary>
        /// This method will load the required control(passed in as parameter)with the options
        /// </summary>
        /// <param name="qV">The q V.</param>
        /// <param name="controlCollection">The control collection.</param>
        private void AddOptionsToControl(QuestionnaireVersion qV, Hashtable controlCollection)
        {
            if (qV != null)
            {
                foreach (DictionaryEntry itemEntry in controlCollection)
                {
                    foreach (QuestionnaireItem item in qV.Items)
                    {
                        if (itemEntry.Key.ToString().ToLower() == item.Name.ToLower())
                        {
                            Control c = (Control) itemEntry.Value;

                            if (c.GetType().ToString() == "System.Web.UI.WebControls.DropDownList")
                            {
                                DropDownList dropdown = (DropDownList) c;
                                ArrayList ar = item.Options;
                                ItemOption defaultOption = (ItemOption) ar[0];
                                if (defaultOption.OptionValue != "Select")
                                {
                                    ItemOption option = new ItemOption(cachePolicy);
                                    option.OptionText = "-- Select --";
                                    option.OptionValue = (defaultOption.OptionValue != "0") ? "0" : "-1";
                                    ar.Insert(0, option);
                                }
                                dropdown.DataSource = ar;
                                dropdown.DataTextField = "OptionText";
                                dropdown.DataValueField = "OptionValue";
                                dropdown.DataBind();
                                break;
                            }

                            if (c.GetType().ToString() == "System.Web.UI.WebControls.ListBox")
                            {
                                ListBox listBox = (ListBox) c;
                                listBox.DataSource = item.Options;
                                listBox.DataTextField = "OptionText";
                                listBox.DataValueField = "OptionValue";
                                listBox.SelectionMode = ListSelectionMode.Multiple;
                                listBox.DataBind();
                                break;
                            }
                        }
                    }
                }
            }
        }

        /// <summary>
        /// returns the search criteria in a hashtable
        /// </summary>
        /// <returns></returns>
        private Hashtable GetSeachCriteriaHash()
        {
            Hashtable searchHash = new Hashtable();
            searchHash.Add("firstName", (firstName.Text.Trim() == string.Empty) ? (object) DBNull.Value : firstName.Text.Trim());
            searchHash.Add("lastName", (lastName.Text.Trim() == string.Empty) ? (object) DBNull.Value : lastName.Text.Trim());
            searchHash.Add("userName", (userName.Text.Trim() == string.Empty) ? (object) DBNull.Value : userName.Text.Trim());
            searchHash.Add("startDate", (startDate.Selection.Trim() == string.Empty) ? (object) DBNull.Value : startDate.Selection.Trim());
            searchHash.Add("endDate", (endDate.Selection.Trim() == string.Empty) ? (object) DBNull.Value : endDate.Selection.Trim());
            searchHash.Add("role", (role.SelectedIndex == -1) ? (object) DBNull.Value : GetListBoxSelections(role)); //Needs to be changed to multiple value search in the query
            searchHash.Add("nothingToDisclose", (disclose.Checked) ? 1 : 0);
            searchHash.Add("outsideEntityName", (companyName.Text.Trim() == string.Empty) ? (object) DBNull.Value : companyName.Text.Trim());
            searchHash.Add("businessNature", (bussinessNatureOfOutsideEntity.SelectedIndex == 0) ? (object) DBNull.Value : bussinessNatureOfOutsideEntity.SelectedValue);
            searchHash.Add("companyType", (companyType.SelectedIndex == 0) ? (object) DBNull.Value : companyType.SelectedValue);
            searchHash.Add("percentageTotalEquityOwned", (perTotalEquityOwned.SelectedIndex == 0) ? (object) DBNull.Value : perTotalEquityOwned.SelectedValue);

            StringBuilder selectedCharts = null;

            if (selectChart.Items[0].Selected)
            {
                searchHash.Add("serviceProvided", (serviceType.SelectedIndex == 0) ? (object) DBNull.Value : serviceType.SelectedValue);
                searchHash.Add("annualEquityCompensation", (annualEquity.SelectedIndex == 0) ? (object) DBNull.Value : annualEquity.SelectedValue); //Needs to be changed to multiple value search in the query
                searchHash.Add("fiduciaryPosition", (selectPosition.SelectedIndex == 0) ? (object) DBNull.Value : selectPosition.SelectedValue);
                searchHash.Add("valueOfEquityOwned", (equityOwned.SelectedIndex == -1) ? (object) DBNull.Value : equityOwned.SelectedValue);
                searchHash.Add("writtenAgreement", (selectWrittenAgreementAnswered.SelectedIndex == 0) ? (object) DBNull.Value : selectWrittenAgreementAnswered.SelectedValue);
                searchHash.Add("daysOfOutsideActivity", (outsideActivityDays.Text.Trim() == String.Empty) ? (object) DBNull.Value : outsideActivityDays.Text.Trim());
                searchHash.Add("isAggregateEquity", (indAggEquityTotal.Checked) ? 1 : 0);
                searchHash.Add("annualCashCompensation", (incomeOutsideActivity.SelectedIndex == 0) ? (object) DBNull.Value : incomeOutsideActivity.SelectedValue); //Needs to be changed to multiple value search in the query
                searchHash.Add("csrlReview", (csrlReview.SelectedIndex == 0) ? (object) DBNull.Value : csrlReview.SelectedValue); //Needs to be changed to multiple value search in the query

                selectedCharts = new StringBuilder();
                selectedCharts.Append("'Chart1'");
            }

            if (selectChart.Items[1].Selected)
            {
                searchHash.Add("chart2ValueOfEquityInterest", (equityinterest.SelectedIndex == 0) ? (object) DBNull.Value : equityinterest.SelectedValue);
                if (selectedCharts != null)
                {
                    selectedCharts.Append(",'Chart2'");
                }
                else
                {
                    selectedCharts = new StringBuilder();
                    selectedCharts.Append("'Chart2'");
                }
            }

            if (selectChart.Items[2].Selected)
            {
                searchHash.Add("familyMember", (memberAssosiated.SelectedIndex == 0) ? (object) DBNull.Value : memberAssosiated.SelectedValue);
                searchHash.Add("familyMemberAssociation", (memberRelation.SelectedIndex == 0) ? (object) DBNull.Value : memberRelation.SelectedValue);
                searchHash.Add("chart3ValueOfEquityInterest", (valueEquityInterest.SelectedIndex == 0) ? (object) DBNull.Value : valueEquityInterest.SelectedValue);
                if (selectedCharts != null)
                {
                    selectedCharts.Append(",'Chart3'");
                }
                else
                {
                    selectedCharts = new StringBuilder();
                    selectedCharts.Append("'Chart3'");
                }
            }

            if (selectChart.Items[3].Selected)
            {
                searchHash.Add("isPayedByPartners", (isPayedByPartners.SelectedIndex == 0) ? (object) DBNull.Value : isPayedByPartners.SelectedValue);
                searchHash.Add("paymentNature", (paymentNature.SelectedIndex == 0) ? (object) DBNull.Value : paymentNature.SelectedValue);
                searchHash.Add("paymentPurpose", (paymentPurpose.SelectedIndex == 0) ? (object) DBNull.Value : paymentPurpose.SelectedValue);
                searchHash.Add("annualPayment", (annulaPayment.SelectedIndex == 0) ? (object) DBNull.Value : annulaPayment.SelectedValue);
                if (selectedCharts != null)
                {
                    selectedCharts.Append(",'Chart4'");
                }
                else
                {
                    selectedCharts = new StringBuilder();
                    selectedCharts.Append("'Chart4'");
                }
            }

            if (selectOutsideTrusteeChart.Items[0].Selected)
            {
                searchHash.Add("nonPartnerAssociation", (nonPartnerAssociation.SelectedIndex == 0) ? (object) DBNull.Value : nonPartnerAssociation.SelectedValue);
                searchHash.Add("oMdescOfOutsideEntity", (briefDescOfNonPartnersEntity.SelectedIndex == 0) ? (object) DBNull.Value : briefDescOfNonPartnersEntity.SelectedValue);
                if (selectedCharts != null)
                {
                    selectedCharts.Append(",'TrusteeChart1'");
                }
                else
                {
                    selectedCharts = new StringBuilder();
                    selectedCharts.Append("'TrusteeChart1'");
                }
            }
            if (selectOutsideTrusteeChart.Items[1].Selected)
            {
                searchHash.Add("oTFamilyMember", (associatedFamilyMember.SelectedIndex == 0) ? (object) DBNull.Value : associatedFamilyMember.SelectedValue);
                if (selectedCharts != null)
                {
                    selectedCharts.Append(",'TrusteeChart2'");
                }
                else
                {
                    selectedCharts = new StringBuilder();
                    selectedCharts.Append("'TrusteeChart2'");
                }
            }
            searchHash.Add("selectedCharts", (selectedCharts != null) ? selectedCharts.ToString() : (object) DBNull.Value);

            return searchHash;
        }

        /// <summary>
        /// Uncaches COiUserSummary object from cache.
        /// </summary>
        private void PurgeCache()
        {
            System.Diagnostics.Trace.WriteLine("Purging Custom report summary...");
            COIUserSummary coiUserSummary = GetCOIUserSummaryFromCache;
            if (coiUserSummary != null)
            {
                coiUserSummary.Purge();
                cachePolicy.UnCache(COIUserSummary.CacheKey);
            }
        }

        /// <summary>
        /// This method will concatenate the selected values(multiple selections) in the listbox.
        /// </summary>
        /// <param name="lb">listbox for which the selected values has to be concatenated</param>
        /// <returns>string of selected values separated by a comma(,)</returns>
        private static string GetListBoxSelections(ListControl lb)
        {
            StringBuilder selectedItems = null;

            if (lb.SelectedIndex != -1)
            {
                selectedItems = new StringBuilder(string.Empty);
                foreach (ListItem li in lb.Items)
                {
                    if (li.Selected)
                    {
                        selectedItems = (selectedItems.ToString() == string.Empty) ? selectedItems.Append("'" + li.Value.Trim()) : selectedItems.Append("','" + li.Value.Trim());
                    }
                }
                if (selectedItems.ToString() != string.Empty)
                {
                    selectedItems.Append("'");
                }
            }
            return selectedItems.ToString();
        }

        /// <summary>
        /// Initilize the first record, last record and current page values for the pager controls.
        /// Set the current page index to 0 and manage navigation links.
        /// </summary>
        private void InitializePager()
        {
            bottomPager.FirstRecord = topPager.FirstRecord = 1;
            bottomPager.LastRecord = topPager.LastRecord =
                Math.Min(coiReportGrid.PageSize, coiReportGrid.Items.Count);
            bottomPager.CurrentPage = topPager.CurrentPage = 1;
            CurrentPageIndex = 0;
            ManageNavigationLinks();
        }

        /// <summary>
        /// Enables or Disables links to other pages within the grid
        /// </summary>
        private void ManageNavigationLinks()
        {
            bottomPager.EnableFirstPage = topPager.EnableFirstPage =
                bottomPager.EnablePreviousPage = topPager.EnablePreviousPage =
                    (coiReportGrid.CurrentPageIndex != 0);

            bottomPager.EnableLastPage = topPager.EnableLastPage =
                bottomPager.EnableNextPage = topPager.EnableNextPage =
                    (coiReportGrid.CurrentPageIndex != (topPager.PageCount - 1));
        }

        /// <summary>
        /// Pagination management
        /// </summary>
        private void ManagePagination()
        {
            int currentPageIndex = CurrentPageIndex;
            coiReportGrid.CurrentPageIndex = currentPageIndex;

            int startIndex = currentPageIndex*coiReportGrid.PageSize;
            bottomPager.FirstRecord = topPager.FirstRecord = startIndex + 1;

            int lastRecord = GetCOIUserSummaryFromCache.Count;
            bottomPager.LastRecord = topPager.LastRecord =
                Math.Min(startIndex + coiReportGrid.PageSize, lastRecord);
        }

        /// <summary>	
        /// Loads the COIUser Summary details only for those to displayed on the page.
        /// </summary>
        private void LoadDataGrid()
        {
            COIUserSummary cOIUserSummary = COIUserSummary;
            if (cOIUserSummary != null && cOIUserSummary.GetDataContainer().Tables.Count > 0)
            {
                coiReportGrid.VirtualItemCount = bottomPager.RecordCount =
                    topPager.RecordCount = cOIUserSummary.Count;
                int currentPageIndex = CurrentPageIndex;
                int pageCount = (topPager.RecordCount/coiReportGrid.PageSize) + (((topPager.RecordCount%coiReportGrid.PageSize) == 0) ? 0 : 1);
                bottomPager.PageCount = topPager.PageCount = pageCount;
                bottomPager.CurrentPage = topPager.CurrentPage = currentPageIndex + 1;

                DataTable table = cOIUserSummary.GetSummaryList(
                    currentPageIndex*coiReportGrid.PageSize, coiReportGrid.PageSize, DataAccess.ConnectionString, ReferrencePageIndex);
                coiReportGrid.DataSource = table;
                coiReportGrid.DataKeyField = KeyField;
                coiReportGrid.DataBind();

                // Add reporting parameters to session in case this page needs to be downloaded to excel/pdf
                Hashtable sqlReportingParams = new Hashtable();
                sqlReportingParams.Add(SqlReportingParamNameXml, cOIUserSummary.GetDataContainer().GetXml());
                Session[Common.Constants.SessionVarNameSsrsReportParams] = sqlReportingParams;

                if (table.Rows.Count == 0)
                {
                    gridContainer.Visible = false;
                    annunciator.Message = "The search criteria yielded no results.";
                }
                else
                {
                    gridContainer.Visible = true;
                    annunciator.Message = string.Empty;
                    recordCount.Text = topPager.RecordCount.ToString();
                    ManagePagination();
                    ManageNavigationLinks();
                }
            }
            else
            {
                gridContainer.Visible = false;
                annunciator.Message = "The search criteria yielded no results.";
            }
        }

        /// <summary>
        /// Loads the COIRoles available in the listbox for search
        /// </summary>
        private void LoadRole()
        {
            RefCodes refCodes =
                (RefCodes) ((ICachePolicy) Page.Application[Names.ApplicationCachePolicyKey]).GetCachedObject(RefCodes.CacheKey);

            ArrayList COIUserRole = refCodes.GetSortedRefCodes(COI.Constants.COIRole.Domain, COI.Constants.COIRole.AttributeOrder);

            foreach (RefCode refCode in COIUserRole)
            {
                role.Items.Add(new ListItem(refCode.Meaning, refCode.Code));
            }
            role.SelectedIndex = -1;
            role.Enabled = (role.Items.Count > 1);
        }

        /// <summary>
        /// Resets the search criteria to the default values depending on the control type(using reflection)
        /// </summary>
        private void ResetSearchCriteria(Control c)
        {
            foreach (Control panelControl in c.Controls)
            {
                if (panelControl.GetType().ToString() == "System.Web.UI.WebControls.ListBox")
                {
                    ((ListBox) panelControl).SelectedIndex = -1;
                }
                else if (panelControl.GetType().ToString() == "System.Web.UI.WebControls.DropDownList")
                {
                    ((DropDownList) panelControl).SelectedIndex = 0;
                }
                else if (panelControl.GetType().ToString() == "System.Web.UI.WebControls.TextBox")
                {
                    ((TextBox) panelControl).Text = string.Empty;
                }
                else if (panelControl.GetType().ToString() == "System.Web.UI.WebControls.CheckBox")
                {
                    ((CheckBox) panelControl).Checked = false;
                }
                else if (panelControl.GetType().ToString() == "System.Web.UI.WebControls.CheckBoxList")
                {
                    ((CheckBoxList) panelControl).SelectedIndex = -1;
                }
                else if (panelControl.GetType().ToString() == "System.Web.UI.WebControls.Panel")
                {
                    ResetSearchCriteria(panelControl);
                }
                else if (panelControl.GetType().ToString() == "PHSRAG.WebControls.Calendar")
                {
                    ((Calendar) panelControl).Reset();
                }
            }

            searchChart1.Visible = false;
            searchChart2.Visible = false;
            searchChart3.Visible = false;
            associatedFamilyMember.Enabled = false;
            outsideTrusteeChart.Visible = false;
            gridContainer.Visible = false;
            selectChart.Enabled = true;
            selectOutsideTrusteeChart.Enabled = true;
        }

        #endregion

        #region ColumnIndex Enum

        /// <summary>
        /// Provides indexes used in the datagrid for specific columns
        /// </summary>
        private enum ColumnIndex
        {
            /// <summary>Current COI Id column index (hidden)</summary>
            Id,
            /// <summary>Name column index </summary>
            Name,
            /// <summary>Supervisor column index </summary>
            Supervisor,
            /// <summary>Title </summary>
            Title,
            /// <summary>PolicyQuestion column index (hidden)</summary>
            PolicyQuestion,
            /// <summary>OutsideActivity column index (hidden)</summary>
            OutsideActivity,
            ///<summary>EquityInterest column index</summary>
            EquityInterest,
            /// <summary>FamilyInterest column index</summary>
            FamilyInterset,
            /// <summary>OtherActivity column index</summary>
            OtherActivity,
            /// <summary>Royalty Column index</summary>
            Royalty,
            /// <summary>Current COI Column index</summary>
            CurrentCOI,
            /// <summary>Last submitted date</summary>
            LastSubmitted,
            /// <summary>Document Id(Report Id from the database)</summary>
            DocumentId
        }

        #endregion
    }
}